/**
 *It is a demo for practicing JAVA. All codes are opened source by Jian.
 */
package jian.tool.daocode.util;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Jian
 * @date 2012-6-28
 * @version
 * 
 */
public class TreeHelper
{

    /**
     * 
     * @return 所有的可连接的数据库名称
     */
    public static List<String> getDatabases()
    {
        Connection conn = null;
        DatabaseMetaData metaData = null;
        ResultSet rs = null;
        List<String> databases = new ArrayList<String>();
        try
        {
            conn = JdbcUtil.getConn();
            metaData = conn.getMetaData();
            rs = metaData.getCatalogs();
            while (rs.next())
            {
                String database = rs.getString("TABLE_CAT");
                System.err.println(database);
                databases.add(database);
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }
        finally
        {
            JdbcUtil.close(rs, null, conn);
        }
        return databases;
    }

    /**
     * 
     * @param dbName
     * @return 所有当前数据库的表名
     */
    public static List<String> getTables(String dbName)
    {
        Connection conn = null;
        DatabaseMetaData metaData = null;
        ResultSet rs = null;
        List<String> tables = new ArrayList<String>();
        try
        {
            conn = JdbcUtil.getConn(dbName);
            metaData = conn.getMetaData();
            rs = metaData.getTables(null, null, null, new String[] { "TABLE" });

            while (rs.next())
            {
                String tableName = rs.getString("TABLE_NAME");
                tables.add(tableName);
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }
        finally
        {
            JdbcUtil.close(rs, null, conn);
        }
        return tables;
    }
}
